package com.bilin.coin.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.bilin.coin.ApiConstant;
import com.bilin.coin.MainActivity;
import com.bilin.coin.R;
import com.bilin.coin.bean.AnnoBean;
import com.bilin.coin.bean.BannerBean;
import com.bilin.coin.bean.BiLinWallet;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.DigStatusBean;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.common.base.BaseFragment;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.tools.AlertUtils;
import com.bilin.coin.tools.Geter;
import com.bilin.coin.tools.Poster;
import com.bilin.coin.utils.DateUtil;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.GlideUtils;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.MoneyUtils;
import com.sunfusheng.marqueeview.MarqueeView;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kt.com.bilin.coin.ad.AdManager;
import kt.com.bilin.coin.ad.FusionAdManager;
import kt.com.bilin.coin.utils.GlideImageLoader;

public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout sw_refresh;
    @BindView(R.id.tv_gold)
    TextView tv_gold;
    @BindView(R.id.tv_seed)
    TextView tv_seed;
    @BindView(R.id.tv_point)
    TextView tv_point;
    @BindView(R.id.tv_jx)
    TextView tv_jx;
    @BindView(R.id.tv_gen_amount)
    TextView tv_gen_amount;
    @BindView(R.id.tv_time_or_dig)
    TextView tv_time_or_dig;
    @BindView(R.id.tv_more_announcement)
    TextView tv_more_announcement;

    @BindView(R.id.iv_out_circle)
    ImageView iv_out_circle;
    @BindView(R.id.iv_inner_circle)
    ImageView iv_inner_circle;
    @BindView(R.id.iv_speed)
    ImageView iv_speed;
    @BindView(R.id.iv1)
    ImageView iv1;

    List<AnnoBean.RecordsBean> listMarqueeData = new ArrayList<>();
    private BiLinWallet biLinWallet;
    private DigStatusBean digStatusBean;
    private CountDownTimer timer;

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initRefresh();
        getBanner();
        getAnnoData();
        getWallet();
        getDigStatus();
    }

    private void getDigStatus() {
        new Geter((BaseAppCompatActivity) mContext, false, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-dig/getStatus";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                digStatusBean = GsonUtil.GsonToBean(dataJson, DigStatusBean.class);
                fillDigStatus();
            }
        };
    }


    Double hadAmount;

    private void fillDigStatus() {
        if (digStatusBean == null) return;
        hadAmount = Double.parseDouble(MoneyUtils.decimal2ByUp2(new BigDecimal(digStatusBean.getHadAmount())));
        tv_gen_amount.setText("已产出 " + digStatusBean.getHadAmount());
        switch (digStatusBean.getDigStatus()) {// 0-在挖 1-待收 2-已收(今日可挖) 3-已收（今日不可挖）
            case "0":
                if (timer != null) timer.cancel();
                tv_gen_amount.setVisibility(View.VISIBLE);

                iv_inner_circle.setVisibility(View.GONE);
                tv_time_or_dig.setText("剩余:" + digStatusBean.getRemainSecond());
                tv_time_or_dig.setTextColor(getResources().getColor(R.color.colorBlue));
                tv_time_or_dig.setClickable(false);

                GlideUtils.getInstance().loadGifImage(mContext, R.mipmap.mill_dt, iv1);
                //iv_speed.setVisibility(View.VISIBLE);
                if (digStatusBean.isCanSpeed()) {
                    iv_speed.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //showAd();
                            initAndPlayAd();
                        }
                    });
                } else {
                    iv_speed.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showToast("今日已加速，每日只可加速一次");
                        }
                    });
                }

                timer = new CountDownTimer(Long.parseLong(digStatusBean.getRemainSecond()) * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tv_time_or_dig.setText("" + DateUtil.getDiffDDHHMMSS(millisUntilFinished + ""));
                        hadAmount += Double.parseDouble(digStatusBean.getJdPerSecond());
                        tv_gen_amount.setText("已产出 " + MoneyUtils.decimal8ByUp(new BigDecimal(hadAmount)));
                    }

                    @Override
                    public void onFinish() {
                        if (Long.parseLong(digStatusBean.getRemainSecond()) > 0) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getDigStatus();
                                }
                            }, 5000);
                        }
                    }
                }.start();
                break;
            case "1":
                if (timer != null) timer.cancel();
                tv_gen_amount.setVisibility(View.VISIBLE);
                iv_inner_circle.setVisibility(View.GONE);
                //.setVisibility(View.VISIBLE);
                iv_speed.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showToast("您今日已完成挖矿，不可进行加速");
                    }
                });
                tv_time_or_dig.setTextColor(getResources().getColor(R.color.colorBlue));
                tv_time_or_dig.setText("领取金豆");
                tv_time_or_dig.setClickable(true);
                tv_time_or_dig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shou();
                    }
                });
                iv1.setImageResource(R.mipmap.mill_dt);
                break;
            case "2":
                if (timer != null) timer.cancel();
                tv_gen_amount.setVisibility(View.GONE);
                //iv_speed.setVisibility(View.VISIBLE);
                iv_speed.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showToast("您还未开始挖矿，不可进行加速");
                    }
                });
                iv_inner_circle.setVisibility(View.VISIBLE);
                tv_time_or_dig.setText("开始挖矿");
                tv_time_or_dig.setTextColor(getResources().getColor(R.color.whiteMain));
                tv_time_or_dig.setClickable(true);
                tv_time_or_dig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dig();
                    }
                });
                iv1.setImageResource(R.mipmap.mill_dt);
                break;
            case "3":
                if (timer != null) timer.cancel();
                tv_gen_amount.setVisibility(View.VISIBLE);
                iv_inner_circle.setVisibility(View.GONE);
                //iv_speed.setVisibility(View.VISIBLE);
                iv_speed.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showToast("您今日已完成挖矿，不可进行加速");
                    }
                });
                tv_time_or_dig.setTextColor(getResources().getColor(R.color.colorBlue));
                tv_time_or_dig.setText("已领取");
                tv_time_or_dig.setClickable(false);
                iv1.setImageResource(R.mipmap.mill_dt);
                break;
        }
    }

    private void shou() {
        new Poster((BaseAppCompatActivity) mContext, true, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-dig/cat";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                getDigStatus();
                getWallet();
            }
        };
    }

    private void dig() {
        new Poster((BaseAppCompatActivity) mContext, true, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-dig/dig";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                getDigStatus();
            }
        };
    }

    @OnClick({R.id.iv_invite, R.id.ll_buy, R.id.llJiayou,
            R.id.ll_live, R.id.ll_activity_area,
            R.id.ll_daily_task, R.id.ll_mall, R.id.ll_gold_bean,
            R.id.ll_seed, R.id.ll_jixiao, R.id.ll_points, R.id.ll_team,
            R.id.tv_more_announcement
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_more_announcement:
                baseStartActivity("/mall/NewsListActivity");
                break;
            case R.id.iv_invite:
                baseStartActivity("/auction/InviteActivity");
                break;
            case R.id.ll_buy:
            case R.id.ll_live:
            case R.id.ll_activity_area:
            case R.id.ll_mall:
                showWaitDev();
                break;
            case R.id.ll_daily_task:
                ((MainActivity) mContext).switchTaskTab();
                break;
            case R.id.ll_points:
                baseStartActivity("/auction/PointDetailActivity");
                break;
            case R.id.ll_jixiao:
                baseStartActivity("/auction/JiXiaoDetailActivity");
                break;
            case R.id.ll_seed:
                baseStartActivity("/auction/SeedDetailActivity");
                break;
            case R.id.ll_gold_bean:
                baseStartActivity("/auction/GoldBeanDetailActivity");
                break;
            case R.id.ll_team:
                baseStartActivity("/auction/MyTeamActivity");
                break;
            case R.id.llJiayou:
                baseStartActivityWith("/common/WebPageLoading")
                        .withString("url", "https://open.czb365.com/redirection/todo?platformType=92652715&platformCode=18210016397")
                        .withString("title", "加油优惠")
                        .navigation();
                break;

        }
    }

    private void showWaitDev() {
        AlertUtils.dialog((Activity) mContext, new AlertUtils.OnPositiveClick() {
            @Override
            public void onClick() {

            }
        });
    }

    private void getWallet() {
        new Geter((BaseAppCompatActivity) mContext, false, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-wallet/getMoney";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                biLinWallet = GsonUtil.GsonToBean(dataJson, BiLinWallet.class);
                fillWallet();
            }
        };
    }

    private void fillWallet() {
        tv_gold.setText(biLinWallet.getJd());
        tv_seed.setText(biLinWallet.getZz());
        tv_point.setText(biLinWallet.getGf());
        tv_jx.setText(biLinWallet.getJx());
    }

    private void initRefresh() {
        //设置样式刷新显示的位置
        sw_refresh.setProgressViewOffset(true, -20, 100);
        sw_refresh.setOnRefreshListener(this);
        //解决滑动冲突
      /*  appbar_layout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0) {
                    sw_refresh.setEnabled(true);
                } else {
                    sw_refresh.setEnabled(false);

                }
            }
        });*/
        sw_refresh.setEnabled(true);
    }

    private void getBanner() {
        //DialogUtils.showDialogLoading(mContext);
        RequestUtils
                .get()
                .url("/api/bl-banner/list")
                .addParams("type", "1")
                .build()
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new CommonCallBack() {
                    @Override
                    protected void onError(String errorMsg) {
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        List<BannerBean.RecordsBean> bannerBean = GsonUtil.jsonToList(dataJson, BannerBean.RecordsBean.class);
                        initBanner(bannerBean, banner, 0);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });
    }


    private void initBanner(List<BannerBean.RecordsBean> recordsBeans, Banner bnHomeBanner_, int radius) {
    /*    //设置banner样式
        bnHomeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        bnHomeBanner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        //bnHomeBanner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        bnHomeBanner.isAutoPlay(true);*/
        if (bnHomeBanner_ == null) {
            showToast("视图未初始化");
            return;
        }
        List<String> cover = new ArrayList<>();
        if (recordsBeans != null) {
            for (BannerBean.RecordsBean recordsBean : recordsBeans) {
                cover.add(ApiConstant.OSSURL + recordsBean.getPicUrl());
            }
        }
        bnHomeBanner_.
                setImageLoader(new GlideImageLoader())
                .setIndicatorGravity(BannerConfig.RIGHT)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setDelayTime(5000)
                .setImages(cover)
                .start();
        bnHomeBanner_.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        bnHomeBanner_.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        bnHomeBanner_.setIndicatorGravity(BannerConfig.CENTER);
    }

    private void initMarqueeView() {
        marqueeView.startWithList(listMarqueeData);
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                AnnoBean.RecordsBean model = (AnnoBean.RecordsBean) marqueeView.getMessages().get(position);
                baseStartActivityWith("/common/WebPageLoading")
                        .withString("url", RetrofitConfig.newsUrl + model.getId())
                        .withString("title", "公告详情")
                        .navigation();
            }
        });
    }

    private void getAnnoData() {
        new Geter((BaseAppCompatActivity) mContext, false, false) {
            @Override
            protected String fillUrl() {
                return "/api/bl-announce/list";
            }

            @Override
            protected Map<String, String> fillParams() {
                HashMap hashMap = new HashMap();
                hashMap.put("currentPage", "1");
                hashMap.put("pageSize", "3");
                return hashMap;
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                AnnoBean newsBean = RequestUtils.getGson().fromJson(dataJson, AnnoBean.class);
                //fillNewsData(newsBean);
                listMarqueeData = newsBean.getRecords();
                initMarqueeView();
            }
        };
    }


    @Override
    protected void initData() {

    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_head;
    }


    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 登录成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.LoginSuccess) {

        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 退出成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void logoutSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.LogoutSuccess) {

        }

        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    @Override
    public void onRefresh() {
        getBanner();
        getAnnoData();
        getDigStatus();
        getWallet();
        sw_refresh.setRefreshing(false);
    }

    private void addOneAd() {
        new Poster((BaseAppCompatActivity) mContext, true, false) {
            @Override
            protected String fillUrl() {
                return "/api/bl-dig/lookVideo";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                getDigStatus();
            }
        };
    }

    private void initAndPlayAd() {
        AdManager.INSTANCE.loadRewardVideoAd(getActivity(), () -> {
            addOneAd();
            return null;
        });
    }
}
